package com.topscore.uke.mvp.model;

import com.topscore.uke.entities.VisitorChartBean;
import com.topscore.uke.entities.VisitorSourceEntity;
import com.topscore.uke.mvp.contractors.GetMyVisitorsContractor;
import com.topscore.uke.network.BaseResponse;
import com.topscore.uke.network.request.GetVisitorSourceRequest;
import com.topscore.uke.network.request.GetVisitorsChartRequest;
import com.topscore.uke.network.retrofit.HandleErrorSubscriber;

import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 71468 on 2017/10/27.
 */

public class GetMyVisitorsModel implements GetMyVisitorsContractor.Model, GetMyVisitorsContractor {

    private CallBack mCallBack;

    public GetMyVisitorsModel(CallBack callBack) {
        this.mCallBack = callBack;
    }

    @Override
    public void getVisitorsChartData(String userId) {
        GetVisitorsChartRequest request = new GetVisitorsChartRequest();
        request.setShareUserId(userId);
        mService.getVisitorsCount(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new HandleErrorSubscriber<BaseResponse<List<VisitorChartBean>>>(mCallBack) {
                    @Override
                    public void onSuccess(BaseResponse<List<VisitorChartBean>> response) {
                        mCallBack.onGetChartDataSuccess(response);
                    }
                });
    }

    @Override
    public void getData(String userId) {
        GetVisitorsChartRequest chartRequest = new GetVisitorsChartRequest();
        GetVisitorSourceRequest sourceRequest = new GetVisitorSourceRequest();
        chartRequest.setShareUserId(userId);
        sourceRequest.setShareUserId(userId);
        Observable.merge(mService.getVisitorSource(sourceRequest), mService.getVisitorsCount(chartRequest))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new HandleErrorSubscriber<BaseResponse<? extends List<?>>>(mCallBack) {
                    @Override
                    public void onSuccess(BaseResponse<? extends List<?>> response) {
                        if (response.getData() != null && !response.getData().isEmpty()){
                            if (response.getData().get(0) instanceof VisitorChartBean){
                                mCallBack.onGetChartDataSuccess((BaseResponse<List<VisitorChartBean>>) response);
                            }else if (response.getData().get(0) instanceof VisitorSourceEntity){
                                mCallBack.onGetVisitorSourceDataSuccess((BaseResponse<List<VisitorSourceEntity>>) response);
                            }
                        }
                    }
                });
    }
}
